package cn.xingzhe.monster.user.infrastructure.repository.impl;

import cn.xingzhe.monster.user.domain.model.RoleModel;
import cn.xingzhe.monster.user.domain.repository.RoleRepository;
import cn.xingzhe.monster.user.infrastructure.persistence.converter.RoleEntityConverter;
import cn.xingzhe.monster.user.infrastructure.persistence.entity.RoleEntity;
import cn.xingzhe.monster.user.infrastructure.repository.RoleMongoRepository;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * MongoDB 角色仓储实现
 * 内部操作 RoleEntity，对外返回 RoleModel
 *
 * @author System
 * @version 1.0.0
 * @since 2024-01-01
 */
@Component
public class MongoRoleRepository implements RoleRepository {

    private final RoleMongoRepository mongoRepository;

    public MongoRoleRepository(RoleMongoRepository mongoRepository) {
        this.mongoRepository = mongoRepository;
    }

    @Override
    public Optional<RoleModel> findById(String id) {
        return mongoRepository.findById(id)
                .map(RoleEntityConverter::toModel);
    }

    @Override
    public Optional<RoleModel> findByRoleCode(String roleCode) {
        return mongoRepository.findByRoleCode(roleCode)
                .map(RoleEntityConverter::toModel);
    }

    @Override
    public List<RoleModel> findByIds(List<String> ids) {
        List<RoleEntity> entities = mongoRepository.findAllById(ids);
        return entities.stream()
                .map(RoleEntityConverter::toModel)
                .collect(Collectors.toList());
    }

    @Override
    public RoleModel save(RoleModel role) {
        RoleEntity entity = RoleEntityConverter.toEntity(role);
        RoleEntity savedEntity = mongoRepository.save(entity);
        return RoleEntityConverter.toModel(savedEntity);
    }

    @Override
    public void deleteById(String id) {
        mongoRepository.deleteById(id);
    }

    @Override
    public List<RoleModel> findAll() {
        List<RoleEntity> entities = mongoRepository.findAll();
        return entities.stream()
                .map(RoleEntityConverter::toModel)
                .collect(Collectors.toList());
    }

}

